/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence.dao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import persistence.interfaces.IFilesystemDao;
import persistence.services.BaseDao;
import persistence.services.PersistenceException;
import utils.BaseModel;
import utils.SmLogFactory;

/**
 *
 * @author jmoura
 */
public class FilesystemDao extends BaseDao implements IFilesystemDao, Serializable {

    private static final Log log = SmLogFactory.getLog(FilesystemDao.class);
    public static final String IMAGES_FOLDER = "images/";

    /**
     * no DB interaction.
     *
     * @param rs
     * @return
     * @throws SQLException
     * @throws PersistenceException
     */
    @Override
    protected BaseModel loadColumns(ResultSet rs) throws SQLException, PersistenceException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Boolean createFolder(String nmFolder) throws PersistenceException {
        boolean success = true;
        //create base dir
        if (!(new File(nmFolder)).exists()) {
            success = (new File(nmFolder)).mkdir();
        }

        //create defaul image subfile
        String mapaDir = nmFolder + IMAGES_FOLDER;
        if (!(new File(mapaDir)).exists()) {
            success = (new File(mapaDir)).mkdir();
        }
        return success;
    }

    /**
     * Create the file, delete if exists. then open filestream
     *
     * @param nmFile
     * @return
     * @throws PersistenceException
     */
    @Override
    public Boolean createStream(String nmFile) throws PersistenceException {
        //prepare file
        boolean success = false;
        try {
            success = createFile(nmFile);
            System.setOut(new PrintStream(new FileOutputStream(nmFile, true)));
        } catch (FileNotFoundException ex) {
            log.error("Trouble creating file: " + nmFile);
            //then exit
            throw new UnsupportedOperationException("Trouble creating file: " + nmFile);
        }
        return success;
    }

    /**
     * if file exists,then delete it first.
     *
     * @param nmFile
     * @param success
     * @return
     */
    @Override
    public boolean createFile(String nmFile) {
        boolean success = true;
        if ((new File(nmFile)).exists()) {
            success = (new File(nmFile)).delete();
        }
        return success;
    }
}
